﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using skags.Models;

/*
* University of Reykjavík
* Brjóstagjöf.is is the product of first-year practical programming course
* for computer science students at said university
*
* URL: http://code.google.com/p/scags
* Authors: 
* Ástvaldur Sigurðsson
* Guðjón Jónsson
* Kristín Inga Vigfúsdóttir
* Steinar Bragi Sigurðsson
* Sveinn Ernstsson
*/

namespace skags.Controllers
{
    /* 
     * Þessi Controller sér um spjallborðið okkar 
     */

    [HandleError]
    [LogError]
    public class ForumController : Controller
    {
        /* Myndum tengingu við forum- og user repository */
        ForumRepository frep = new ForumRepository();
        UserRepository urep = new UserRepository();

        /* GET: Náum í upphafssíðu */
        [Authorize]
        public ActionResult Index()
        {
            
            return View(frep.Get5AllCat());
        }

        /* GET: Náum í flokk og svo greinar innan hans */
        [Authorize]
        public ActionResult Category(int id)
        {
            ViewData["CategoryName"] = frep.GetForumCategoryByID(id).Title.ToString();
            ViewData["CategoryID"] = id;
            return View(frep.GetThreadsByCatID(id));
        }

        /*
         * Spjallþræðir
         */

        /* GET: Birtir ákveðinn þráð og öll svörin við honum */
        [Authorize]
        public ActionResult Thread(int id)
        {
            
            var result = new ForumThreadAnswerViewModel();
            var thread = frep.GetThreadByID(id);
            var category = frep.GetForumCategoryByID(thread.CategoryID);
            var answers = frep.GetAnswersByThreadID(id);

            result.AuthorName = urep.GetNameByHashID(thread.AuthorID);
            result.UserName = thread.aspnet_User.UserName;
            result.CategoryName = category.Title;
            result.DateCreated = thread.DateCreated;
            result.ThreadID = thread.ID;
            result.ThreadText = thread.ThreadText;
            result.Title = thread.Title;
            result.Answers = answers;
            result.AuthorID = urep.GetIDByHashID(thread.AuthorID);
            result.CategoryID = thread.CategoryID;
            return View(result);
        }

        /* GET: Forum/CreateThread/ - Búum til þráð á spjalli */
        [Authorize]
        public ActionResult CreateThread(int id)
        {

            var allCategories = frep.GetAllCategories();


            ViewData["CategoryName"] = frep.GetForumCategoryByID(id).Title;
            ViewData["CategoryID"] = id;

            return View(new ForumCatViewModel { Categories = allCategories });

        }

        /* POST: Forum/CreateThread/ - Búum til þráð á spjalli */
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult CreateThread(ForumCatViewModel model)
        {
            var urep = new UserRepository();
            var thread = new ForumThread();
            model.CreatorID = urep.GetHashIDByUsername(User.Identity.Name);

            bool ok = true;

            thread.AuthorID = model.CreatorID;
            thread.DateCreated = DateTime.Now;
            thread.CategoryID = model.CategoryID;
            thread.ID = model.ID;
            thread.ThreadText = model.ThreadText;
            thread.Title = model.Title;

            if (String.IsNullOrEmpty(model.ThreadText))
            {
                ModelState.AddModelError("ThreadText", "Þráðurinn má ekki vera tómur");
                ok = false;

            }
            if (String.IsNullOrEmpty(model.Title))
            {
                ModelState.AddModelError("Title", "Titillinn má ekki vera tómur");
                ok = false;
            }

            if (ok == false)
            {
                var allCategories = frep.GetAllCategories();


                ViewData["CategoryName"] = frep.GetForumCategoryByID(thread.CategoryID).Title;
                ViewData["CategoryID"] = thread.CategoryID;

                model.Categories = allCategories;

                return View(model);
   
            }


            frep.AddThread(thread);
            frep.Save();

            return RedirectToAction("Thread", new { id = thread.ID });
      
        }

        /* GET: Forum/Edit - Breytum faerslu á spjallborði */
        [Authorize]
        [ValidateInput(false)]
        public ActionResult Edit(int id)
        {
            ForumThread thread = frep.GetThreadByID(id);
            var allCategories = frep.GetAllCategories();
            ForumCatViewModel result = new ForumCatViewModel { Categories = allCategories };

            ViewData["CategoryID"] = thread.CategoryID;

            if (thread == null)
                return View("NotFound");

            if ((System.Web.HttpContext.Current.User.Identity.Name == thread.aspnet_User.UserName)
            || System.Web.HttpContext.Current.User.IsInRole("Admin"))
            {
                result.ThreadText = thread.ThreadText;
                result.Title = thread.Title;
                result.CategoryID = thread.CategoryID;
                return View(result);
            }

            return RedirectToAction("Thread/" + thread.ID);
        }

        /* POST: Forum/Edit - Breytum faerslu á spjallborði */
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            //Finnum þráðinn sem við ætlum að breyta
            ForumThread thread = frep.GetThreadByID(id);

            //Bætum gömlu gildunum inn
            thread.ThreadText = Request.Form["ThreadText"];
            thread.Title = Request.Form["Title"];
            bool ok = true;


            if (String.IsNullOrEmpty(thread.Title)) //athuga hvort reitir hafi verið rétt út fylltir
            {
                ModelState.AddModelError("Title", "Titillinn má ekki vera tómur"); //birta villur
                ok = false;
            }

            if (String.IsNullOrEmpty(thread.ThreadText))
            {
                ModelState.AddModelError("ThreadText", "Þráðurinn má ekki vera tómur");
                ok = false;
            }

            if(!ok)
            {
                //ef eitthvað fer úrskeiðis verðum við að sækja þráðinn aftur
                var allCategories = frep.GetAllCategories();
                ForumCatViewModel result = new ForumCatViewModel { Categories = allCategories };

                ViewData["CategoryID"] = thread.CategoryID;

                result.ThreadText = thread.ThreadText;
                result.Title = thread.Title;
                result.CategoryID = thread.CategoryID;
                return View(result);
            }
            
            //Vista
            frep.Save();
            //Redirect á þráðinn
            return RedirectToAction("Thread", new { id = thread.ID });

        }

        /* GET: Forum/DeleteThread - Eyðum þraeði af spjallborði */ 
        [Authorize]
        public ActionResult DeleteThread(int id)
        {

            ForumThread thread = frep.GetThreadByID(id);
            if (thread == null)
                return View("NotFound");

            if ((System.Web.HttpContext.Current.User.Identity.Name == thread.aspnet_User.UserName)
              || System.Web.HttpContext.Current.User.IsInRole("Admin"))
            {
                return View(thread);
            }

            else
            {
                return RedirectToAction("AttemptDelete");
            }
        }

        /* POST: Forum/DeleteThread - Eyðum þraeði af spjallborði */
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult DeleteThread(int id, string confirmButton)
        {
            ForumThread thread = frep.GetThreadByID(id);
 
            if (thread == null)
            return View("NotFound");

            

            frep.DeleteAllAnswersByThreadID(id);
            frep.DeleteThread(thread);
            frep.Save();
 
            return View("Deleted");
        }

        /* GET: Sendum póst á stjórnanda ef við teljum að ummaeli á þraeði séu ekki við haefi (sjá notendaskilmála) */
        [Authorize]
        public ActionResult ThreadAbuse(int id)
        {
            ForumThread thread = frep.GetThreadByID(id);
            var threadReader = urep.GetUserByID(urep.GetIDByUsername(System.Web.HttpContext.Current.User.Identity.Name));

            var result = new ForumAbuseViewModel();

            result.Thread = thread;
            result.Reader = threadReader;

            var timestamp = DateTime.Now;

            EmailLogMedia mail = new EmailLogMedia();

            mail.ReportAbuse(thread, threadReader, timestamp);

            return RedirectToAction("Abuse");
        }
        /*
         * Svör
         */


        /* GET: Forum/CreateAnswer/(threadID)
        *  Gefur okkur formið til þess að svara. Hér vistum við upplýsingar um þráðinn sem við 
        * birtum fyrir ofan svar formið, og sendum þær með í view.
         */ 
        [Authorize]
        public ActionResult CreateAnswer(int id)
        {
            var db = new DBDataContext();

            ForumCreateAnswerViewModel model = 
                        (from t in db.ForumThreads
                         where t.ID == id
                         select new ForumCreateAnswerViewModel
                                    {
                                        ThreadID = id,
                                        ThAuthor = t.aspnet_User.UserName,
                                        ThAuthorID = urep.GetIDByUsername(t.aspnet_User.UserName),
                                        ThDateCreated = t.DateCreated,
                                        ThreadText = t.ThreadText,
                                        ThTitle = t.Title,
                                        CategoryName = t.ForumCategory.Title
                                    }).SingleOrDefault();
            return View(model);

        }

        /* POST: /Forum/CreateThread/(threadID)
         * Hér fáum við modelið til baka sem við sendum með get fallinu, ástamt gildum sem við getum vistað inn í ThreadAnwer töflu.
         */ 
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult CreateAnswer(ForumCreateAnswerViewModel answerModel)
        {
            var answer = new ThreadAnswer();
            
            try
            {
                answer.ThreadID = answerModel.ThreadID;
                answer.Answer = answerModel.AnswerText;
                answer.DateCreated = DateTime.Now;
                answer.UserID = urep.GetHashIDByUsername(User.Identity.Name);
                frep.AddAnswer(answer);

                return RedirectToAction("Thread/" + answer.ThreadID);

            }
            
            catch
            {
                
                var db = new DBDataContext();
                ForumCreateAnswerViewModel model =
                        (from t in db.ForumThreads
                         where t.ID == answer.ThreadID
                         select new ForumCreateAnswerViewModel
                         {
                             ThreadID = answer.ThreadID,
                             ThAuthor = t.aspnet_User.UserName,
                             ThAuthorID = urep.GetIDByUsername(t.aspnet_User.UserName),
                             ThDateCreated = t.DateCreated,
                             ThreadText = t.ThreadText,
                             ThTitle = t.Title,
                             CategoryName = t.ForumCategory.Title
                         }).SingleOrDefault();

                ModelState.AddModelError("AnswerText", "Svarið má ekki vera tómt");
                
                return View(model);
            }
            

            

        }

        /* GET: Eyðum svari út af þraeði á spjallborði */
        [Authorize]
        public ActionResult DeleteAnswer(int id)
        {
            ThreadAnswer answer = frep.GetAnswerByID(id);
            int threadID = answer.ThreadID;

            if ((System.Web.HttpContext.Current.User.Identity.Name == answer.aspnet_User.UserName) 
              || System.Web.HttpContext.Current.User.IsInRole("Admin"))
            {
                frep.DeleteAnswer(answer);
                return RedirectToAction("Thread/" + threadID);
            }
            else
            {
                return RedirectToAction("AttemptDelete");
            }
        }

        /* GET: View sem birtist ef þú reynir að eyða einhverju sem þú getur ekki eytt (vörn) */
        [Authorize]
        public ActionResult AttemptDelete(UserInfo info)
        {
            return View(info);
        }

        /* GET: Senda tölvupóst á admin varðandi óviðeigandi svar */
        [Authorize]
        public ActionResult AnswerAbuse(int id)
        {
            var answer = frep.GetAnswerByID(id);
            var threadReader = urep.GetUserByID(urep.GetIDByUsername(System.Web.HttpContext.Current.User.Identity.Name));
            var timestamp = DateTime.Now;

            EmailLogMedia mail = new EmailLogMedia();

            mail.ReportAbuse(answer, threadReader, timestamp);

            return RedirectToAction("Abuse");
        }

        public ActionResult Abuse()
        {
            return View();
        }


    }
}
